//
//  JDSearchViewController.swift
//  DragonWallet
//
//  Created by volantPig on 2024/10/27.
//

import UIKit

class JDSearchViewController: JDBaseViewController {

    ///  临时用 必须删除
    var cellNum = 0
    
    var backButton: UIButton?
    var searchContainerView: UIView?
    var searchInputView: UITextField?
    var searchButton: UIButton?
    
    var classificationView: UIView?
    var mainTableView: UITableView?
    
    var customClassificationView: DraClassicHeadView?
    var goodsTypeTitleList: [String] = ["全部"]
    var goodsTypeModels :[JDGoodsTypeModel?]?
    
    // 选中的分类的code
    var categoryCode = ""
    var goodsModels: [JDGoodsModel?]?
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.setupConfig()
        self.setupUIElements()
        self.getClassificationData()
        self.getNetData()
        // Do any additional setup after loading the view.
    }
    
    func setupConfig() {
        // 这个页面设计是 只做展示  如果需要跳转到商品详情，传回去，用上一个页面去跳转
    }
    
    func setupUIElements() {
         
        self.searchContainerView = UIView()
        self.searchContainerView?.backgroundColor = .white
        self.view.addSubview(self.searchContainerView!)
        self.searchContainerView?.snp.makeConstraints({ make in
            make.leading.equalTo(self.view).offset(53)
            make.trailing.equalTo(self.view).offset(-12)
            make.top.equalTo(self.view).offset(topSaftAreaHeight)
            make.height.equalTo(42)
        })
        self.searchContainerView?.makeCorner(8)
        
        self.searchButton = UIButton(type: .custom)
        self.searchContainerView?.addSubview(self.searchButton!)
        self.searchButton?.snp.makeConstraints({ make in
            make.trailing.equalTo(self.searchContainerView!).offset(-5)
            make.centerY.equalTo(self.searchContainerView!)
            make.height.equalTo(32)
            make.width.equalTo(48)
        })
        self.searchButton?.buttonConfig(normalTitle: "搜索", normalTitleColor: .white, titleFont: UIFont.systemFont(ofSize: 15, weight: .regular), backgroundColor: color("#FA6161"))
        self.searchButton?.addTarget(self, action: #selector(searchAction), for: .touchUpInside)
        self.searchButton?.makeCorner(8)
        
        self.searchInputView = UITextField()
        self.searchContainerView?.addSubview(self.searchInputView!)
        self.searchInputView?.snp.makeConstraints({ make in
            make.height.equalTo(32)
            make.leading.equalTo(self.searchContainerView!).offset(10)
            make.trailing.equalTo(self.searchButton!.snp.leading).offset(-10)
            make.centerY.equalTo(self.searchContainerView!)
        })
        self.searchInputView?.textColor = color("#333333")
        self.searchInputView?.placeholder = "请输入你想要寻找的商品"
        self.searchInputView?.clearButtonMode = .whileEditing
        self.searchInputView?.delegate = self
        self.searchInputView?.returnKeyType = .search
        
        self.backButton = UIButton(type: .custom)
        self.view.addSubview(self.backButton!)
        self.backButton?.snp.makeConstraints({ make in
            make.leading.equalTo(self.view)
            make.trailing.equalTo(self.searchContainerView!.snp.leading)
            make.height.equalTo(42)
            make.centerY.equalTo(self.searchContainerView!)
        })
        
        self.backButton?.addTarget(self, action: #selector(hideSearchVC), for: .touchUpInside)
        self.backButton?.setImage(UIImage(named: "black_back")?.withRenderingMode(.alwaysOriginal), for: .normal)
        
        self.classificationView = UIView()
        self.view.addSubview(self.classificationView!)
        self.classificationView?.snp.makeConstraints({ make in
            make.leading.trailing.equalTo(self.view)
            make.top.equalTo(self.searchContainerView!.snp.bottom).offset(12)
            make.height.equalTo(59)
        })
        self.classificationView?.backgroundColor = .white
        
        
        let moreButton = UIButton(type: .custom)
        self.classificationView?.addSubview(moreButton)
        moreButton.snp.makeConstraints { make in
            make.trailing.equalTo(self.classificationView!).offset(-10)
            make.centerY.equalTo(self.classificationView!)
            make.size.equalTo(CGSizeMake(46, 28))
        }
        moreButton.setTitle("分类", for: .normal)
        moreButton.setImage(UIImage(named: "arrow_black"), for: .normal)
        
        moreButton.titleLabel?.font = UIFont.systemFont(ofSize: 13, weight: .regular)
        moreButton.setTitleColor(color("#333333"), for: .normal)
        moreButton.semanticContentAttribute = .forceRightToLeft
        moreButton.titleEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 4)
        moreButton.addTarget(self, action: #selector(moreButtonAction), for: .touchUpInside)
       
        self.customClassificationView = DraClassicHeadView.init(CGRect(x: 0, y: 0, width: screenWidth-56, height: 44), titles: self.goodsTypeTitleList, index: 0)
        self.customClassificationView?.backgroundColor = .clear
        
        self.classificationView?.addSubview(self.customClassificationView!)
        self.customClassificationView?.snp.makeConstraints({ make in
            make.leading.equalTo(self.classificationView!)
            make.trailing.equalTo(moreButton.snp.leading)
            make.centerY.equalTo(self.classificationView!)
            make.height.equalTo(44)
        })
        self.customClassificationView?.delegate = self
        
        self.mainTableView = UITableView(frame: .zero, style: .plain)
        self.view.addSubview(self.mainTableView!)
        self.mainTableView?.snp.makeConstraints({ make in
            make.leading.trailing.equalTo(self.view)
            make.top.equalTo(self.classificationView!.snp.bottom)
            make.bottom.equalTo(self.view)
        })
        self.mainTableView?.delegate = self
        self.mainTableView?.dataSource = self
        self.mainTableView?.register(JDGoodsListCell.self, forCellReuseIdentifier: "myCell")
        self.mainTableView?.backgroundColor = .commonColor()
        self.mainTableView?.separatorStyle = .none
        
        self.mainTableView?.addRefreshHeader { [weak self] in
            if (self?.searchInputView?.text?.count ?? 0 ) > 0 {
                self?.currentPage = 1
                self?.getNetData(true)
            } else {
                self?.mainTableView?.endRefresh()
            }
        }
        
        self.mainTableView?.addRefreshFooter { [weak self] in
            if (self?.searchInputView?.text?.count ?? 0 ) > 0 {
                self?.currentPage += 1
                self?.getNetData(false)
            } else {
                self?.mainTableView?.endRefresh()
            }
        }
        
    }
    
    @objc func hideSearchVC() {
        self.dismiss(animated: false)
    }
    
    @objc func searchAction() {
        self.view.endEditing(true)
        self.getNetData(true)
    }
    
    override func getNetData(_ isRefresh: Bool = true) {
        guard let searchKey = self.searchInputView?.text else { return  }
        
        var params = [String: Any]()
        // 国家代码
        params["countryCode"] = "all"
        // 商品分类 -- 这个还要改
        if self.categoryCode.count > 0 {
            params["goodsCategory"] = self.categoryCode
        }
        params["pageNumber"] = self.currentPage
        params["pageSize"] = 10
        params["goodsMemberLevel"] = 1
        params["goodsName"] = searchKey

        JDNetWorkRequest(.getGoodsList(params)) { responseStr in
            
            printLog("商品列表信息:\(responseStr)")
            let commonModel = JDCommonModel.deserialize(from: responseStr, designatedPath: "")
            if commonModel?.code == "0" {
                
                if let models = [JDGoodsModel].deserialize(from: responseStr, designatedPath: "data.records") {
                    
                    if isRefresh {
                        self.goodsModels = models
                    } else {
                        self.goodsModels?.append(contentsOf: models)
                    }
                    
                    if models.count < 10 {
                        self.mainTableView?.noMoreData()
                    }
                }
            }
            self.mainTableView?.reloadData()
            self.mainTableView?.endRefresh()
            
        } failure: { error in
            
        } error: { errorCode in
            
        }
    }
    
    @objc func getClassificationData() {
        
        JDNetWorkRequest(.getGoodsType([:])) { responseStr in
            
            printLog("分类信息:\(responseStr)")
            let commonModel = JDCommonModel.deserialize(from: responseStr, designatedPath: "")
            if commonModel?.code == "0" {
                
                if let models = [JDGoodsTypeModel].deserialize(from: responseStr, designatedPath: "data") {
//                    self.needRefreshClassification = false
                    self.goodsTypeModels = models
                    self.goodsTypeTitleList = ["全部"]
                    for typeModel in models {
                        self.goodsTypeTitleList.append(typeModel?.name ?? "异常")
                    }
                    self.categoryCode = models.first??.pid ?? "0"
                    DispatchQueue.main.asyncAfter(deadline: .now()+0.2) {
                        self.customClassificationView?.updateData(self.goodsTypeTitleList, index: 0)
                    }
                }
            }
            
        } failure: { error in
            
        } error: { errorCode in
            
        }
    }
 
    @objc func moreButtonAction() {
        self.changeCustomNavigationBarAlpha(1)
        let classilicationVC = JDClassificationViewController()
        classilicationVC.goodsTypeModels = self.goodsTypeModels
        self.hidesBottomBarPushViewController(classilicationVC)
        classilicationVC.selectedClassificationCompleted = {[weak self] classificationIndex ,selectedId in
            guard let classificationId = selectedId else { return }
            guard let weakSelf = self else { return }
            weakSelf.customClassificationView?.updateData(weakSelf.goodsTypeTitleList, index: classificationIndex+1)
            weakSelf.categoryCode = classificationId
            weakSelf.currentPage = 1
            weakSelf.getNetData(true)
        }
    }
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}

extension JDSearchViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.goodsModels?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "myCell") as? JDGoodsListCell
        cell?.contentView.backgroundColor = .clear
        cell?.selectionStyle = .none
        let goodsModel = self.goodsModels?[indexPath.row]
        cell?.goodsModel = goodsModel
        
        return cell!
    }
    
//    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//        let cell = tableView.dequeueReusableCell(withIdentifier: "myCell")
//        
//        for subV in cell?.contentView.subviews ?? [UIView]() {
//            subV.removeFromSuperview()
//        }
//        
//        let currentModel = self.goodsModels?[indexPath.row]
//        
//        let containerView = UIView()
//        cell?.contentView.addSubview(containerView)
//        containerView.snp.makeConstraints { make in
//            make.leading.trailing.equalTo(cell!.contentView)
//            make.top.equalTo(cell!.contentView)
//            make.bottom.equalTo(cell!.contentView).offset(-10)
//        }
//        containerView.makeCorner(8)
//        containerView.backgroundColor = .yellow
//        
//        
//        let goodsImgV = UIImageView()
//        containerView.addSubview(goodsImgV)
//        goodsImgV.snp.makeConstraints { make in
//            make.leading.equalTo(containerView).offset(12)
//            make.centerY.equalTo(containerView)
//            make.size.equalTo(CGSize(width: 72, height: 72))
//        }
//        goodsImgV.backgroundColor = .blue
//        
//        let goodsNameLabel = UILabel()
//        containerView.addSubview(goodsNameLabel)
//        goodsNameLabel.snp.makeConstraints { make in
//            make.leading.equalTo(goodsImgV.snp.trailing).offset(15)
//            make.top.equalTo(goodsImgV)
//            make.height.equalTo(24)
//            make.trailing.equalTo(containerView).offset(-12)
//        }
//        goodsNameLabel.labelConfig(textAlignment: .left, font: UIFont.systemFont(ofSize: 16, weight: .regular), textColor: color("#333333"), numberOfLines: 1)
//        goodsNameLabel.text = "设计师款 8.8克眼镜框男款日本超轻纯钛"
//        
//        let descriptionLabel = UILabel()
//        containerView.addSubview(descriptionLabel)
//        descriptionLabel.snp.makeConstraints { make in
//            make.leading.equalTo(goodsNameLabel)
//            make.top.equalTo(goodsNameLabel.snp.bottom).offset(4)
//            make.height.equalTo(19)
//        }
//        descriptionLabel.labelConfig(textAlignment: .left, font: UIFont.systemFont(ofSize: 12, weight: .regular), textColor: color(""), numberOfLines: 1)
//        descriptionLabel.text = "产地：日本"
//        
//        let priceLabel = UILabel()
//        containerView.addSubview(priceLabel)
//        priceLabel.snp.makeConstraints { make in
//            make.leading.equalTo(goodsNameLabel)
//            make.bottom.equalTo(goodsImgV).offset(-2)
//            make.height.equalTo(19)
//        }
//        priceLabel.labelConfig(textAlignment: .left, font: UIFont.systemFont(ofSize: 16, weight: .semibold), textColor: color("#333333"), numberOfLines: 1)
//        priceLabel.text = "￥375.00"
//        
//        return cell!
//    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 97+10
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        guard let goodsModel = self.goodsModels?[indexPath.row] else {
            return
        }
        let goodsDetailVC = JDGoodsDetailViewController()
        goodsDetailVC.goodsLogoUrl = goodsModel.goodsMainImgUrl
        goodsDetailVC.goodsID = goodsModel.goodsId
        self.hidesBottomBarPushViewController(goodsDetailVC)
    }
    
}

extension JDSearchViewController: UITextFieldDelegate {
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        print("搜索啊")
        self.cellNum = 5
        self.view.endEditing(true)
        self.getNetData(true)
        self.mainTableView?.reloadData()
        return true
    }
    
    func textFieldShouldClear(_ textField: UITextField) -> Bool {
        
        return true
    }
    
    func textFieldDidBeginEditing(_ textField: UITextField) {
        self.cellNum = 0
        self.mainTableView?.reloadData()
    }
    
}


extension JDSearchViewController: DraClassicHeadViewDelegate {
    func didSelectTitleAt(_ index: Int) {
        if index == 0 {
            self.categoryCode = ""
            self.getNetData()
            
        } else {
            let selectedModel = self.goodsTypeModels?[index-1]
            self.categoryCode = selectedModel?.id ?? "0"
            self.getNetData()
        }
        
    }
}
